package com.irate.fragment;

import org.apache.http.Header;
import org.json.JSONObject;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout.LayoutParams;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.TextView;
import android.widget.Toast;

import com.irate.activity.R;
import com.irate.activity.WelcomeActivity;
import com.irate.dao.UserDAO;
import com.irate.http.AsyncHttpResponseHandler;
import com.irate.model.User;
import com.irate.provider.ContentManager;
import com.irate.provider.SessionLogin;
import com.sromku.simple.fb.SimpleFacebook;
import com.sromku.simple.fb.SimpleFacebook.OnLogoutListener;

public class SettingFragment extends Fragment {

	protected Button logout;
	protected Button change_password;
	protected SimpleFacebook fb;
	protected ProgressDialog dialog;
	protected UserDAO userDao;

	protected TextView setting_display_name;
	protected TextView setting_user_name;
	protected TextView setting_email;
	protected TextView setting_region;

	protected TextView privacy_setting;
	protected String newPass;

	protected int check_index;
	protected View mainView;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mainView = inflater.inflate(R.layout.setting_layout, null);
		return mainView;
	}

	@Override
	public void onActivityCreated(Bundle savedInstanceState) {
		super.onActivityCreated(savedInstanceState);

		init();
		execute();
	}

	private void init() {
		userDao = new UserDAO();
		privacy_setting = (TextView) getActivity().findViewById(
				R.id.setting_privacy);
		logout = (Button) getActivity().findViewById(R.id.my_logout);
		fb = SimpleFacebook.getInstance(getActivity());
		change_password = (Button) getActivity().findViewById(
				R.id.my_change_password);

		if (fb.isLogin()) {
			change_password.setClickable(false);
			change_password.setEnabled(false);
		} else {
			change_password.setClickable(true);
			change_password.setEnabled(true);
		}

		setting_display_name = (TextView) getActivity().findViewById(
				R.id.setting_display_name);
		setting_user_name = (TextView) getActivity().findViewById(
				R.id.setting_user_name);
		setting_email = (TextView) getActivity().findViewById(
				R.id.setting_email);
		setting_region = (TextView) getActivity().findViewById(
				R.id.setting_country);

	}

	private void execute() {

		User u = ContentManager.getInstance().getCurrentUser();
		privacy_setting.setPaintFlags(privacy_setting.getPaintFlags()
				| Paint.UNDERLINE_TEXT_FLAG);

		// if( u.getUser_facebook_id()!= null && u.getUser_facebook_id()!= ""){
		// privacy_setting.setEnabled(false);
		// privacy_setting.setTextColor(Color.GRAY);
		// }
		// else
		// {
		// privacy_setting.setEnabled(true);
		// privacy_setting.setTextColor(Color.BLACK);
		// }

		setting_display_name
				.setText(u.getFirst_name() + " " + u.getLast_name());
		setting_user_name.setText(u.getFirst_name() + " " + u.getLast_name());
		setting_email.setText(u.getEmail());
		setting_region.setText(u.getRegion());

		change_password.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				LayoutInflater inflater = (LayoutInflater) getActivity()
						.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

				View contentView = inflater.inflate(
						R.layout.popup_change_password, null, false);

				final PopupWindow pw = new PopupWindow(contentView,
						LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
						true);
				pw.setBackgroundDrawable(new BitmapDrawable());
				pw.showAtLocation(mainView, Gravity.CENTER, 0, 0);
				
				final EditText edold = (EditText) contentView
						.findViewById(R.id.old_pass);
				final EditText ednew = (EditText) contentView
						.findViewById(R.id.new_pass);
				
				pw.setOnDismissListener(new OnDismissListener() {

					@Override
					public void onDismiss() {
						InputMethodManager imm = (InputMethodManager) getActivity()
								.getSystemService(Context.INPUT_METHOD_SERVICE);
						imm.hideSoftInputFromWindow(edold.getWindowToken(), 0);
					}
				});

				
				Button submit = (Button) contentView.findViewById(R.id.submit);

				submit.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						if (edold.getText().equals("")
								|| ednew.getText().equals("")) {
							Toast.makeText(
									getActivity(),
									getResources().getString(
											R.string.input_not_fault),
									Toast.LENGTH_SHORT).show();
						} else {
							pw.dismiss();
							dialog = ProgressDialog.show(
									getActivity(),
									getResources().getString(
											R.string.changepass),
									getResources().getString(R.string.loading),
									true);
							newPass = ednew.getText().toString().trim();
							userDao.changePassWord(edold.getText().toString()
									.trim(), ednew.getText().toString().trim(),
									handlerChangePass, getActivity(), dialog);
						}
					}
				});

			}
		});

		logout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				dialog = ProgressDialog.show(getActivity(), getResources()
						.getString(R.string.logout),
						getResources().getString(R.string.loading), true);

				if (fb.isLogin())
					fb.logout(new OnLogoutListener() {

						@Override
						public void onFail(String reason) {
							Toast.makeText(getActivity(),
									"Logout facebook fail!", Toast.LENGTH_SHORT)
									.show();
						}

						@Override
						public void onException(Throwable throwable) {

						}

						@Override
						public void onThinking() {

						}

						@Override
						public void onLogout() {
							Toast.makeText(getActivity(), "Logout success!",
									Toast.LENGTH_SHORT).show();

							fb.clean();
						}
					});
				userDao.logout(handlerLogout, getActivity(), dialog);
			}
		});

		privacy_setting.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				LayoutInflater inflater = (LayoutInflater) getActivity()
						.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

				View contentView = inflater.inflate(
						R.layout.popup_private_setting, null, false);

				final PopupWindow pw = new PopupWindow(contentView,
						LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
						true);
				pw.setBackgroundDrawable(new BitmapDrawable());
				pw.showAtLocation(mainView, Gravity.CENTER, 0, 0);

				final TextView on_public = (TextView) contentView
						.findViewById(R.id.open_to_public);
				final TextView only_friend = (TextView) contentView
						.findViewById(R.id.only_friend);
				final TextView anonymise_account = (TextView) contentView
						.findViewById(R.id.anonymise_account);

				check_index = Integer.parseInt(ContentManager.getInstance()
						.getCurrentUser().getUser_setting() == null ? "0"
						: ContentManager.getInstance().getCurrentUser()
								.getUser_setting());
				switch (check_index) {
				case 1:
					on_public.setBackgroundColor(Color.GRAY);
					only_friend.setBackgroundColor(Color.TRANSPARENT);
					anonymise_account.setBackgroundColor(Color.TRANSPARENT);
					break;
				case 2:
					on_public.setBackgroundColor(Color.TRANSPARENT);
					only_friend.setBackgroundColor(Color.GRAY);
					anonymise_account.setBackgroundColor(Color.TRANSPARENT);
					break;
				case 3:
					on_public.setBackgroundColor(Color.TRANSPARENT);
					only_friend.setBackgroundColor(Color.TRANSPARENT);
					anonymise_account.setBackgroundColor(Color.GRAY);
					break;

				default:
					on_public.setBackgroundColor(Color.GRAY);
					only_friend.setBackgroundColor(Color.TRANSPARENT);
					anonymise_account.setBackgroundColor(Color.TRANSPARENT);
					break;
				}

				on_public.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						on_public.setBackgroundColor(Color.GRAY);
						only_friend.setBackgroundColor(Color.TRANSPARENT);
						anonymise_account.setBackgroundColor(Color.TRANSPARENT);

						check_index = 1;
						ContentManager.getInstance().getCurrentUser()
								.setUser_setting("" + check_index);
					}
				});

				only_friend.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						on_public.setBackgroundColor(Color.TRANSPARENT);
						only_friend.setBackgroundColor(Color.GRAY);
						anonymise_account.setBackgroundColor(Color.TRANSPARENT);

						check_index = 2;
						ContentManager.getInstance().getCurrentUser()
								.setUser_setting("" + check_index);
					}
				});

				anonymise_account.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {
						on_public.setBackgroundColor(Color.TRANSPARENT);
						only_friend.setBackgroundColor(Color.TRANSPARENT);
						anonymise_account.setBackgroundColor(Color.GRAY);

						check_index = 3;
						ContentManager.getInstance().getCurrentUser()
								.setUser_setting("" + check_index);
					}
				});

				Button submit = (Button) contentView
						.findViewById(R.id.submit_private_setting);

				submit.setOnClickListener(new OnClickListener() {

					@Override
					public void onClick(View v) {

						dialog = ProgressDialog.show(
								getActivity(),
								getResources().getString(
										R.string.update_private_setting),
								getResources().getString(R.string.loading),
								true);

						userDao.submitPrivateSettingToServer(check_index,
								handlerSetPrivateSetting, getActivity(), dialog);
						pw.dismiss();
					}
				});
			}
		});

	}

	AsyncHttpResponseHandler handlerChangePass = new AsyncHttpResponseHandler() {
		@Override
		public void onSuccess(int statusCode, Header[] headers, byte[] response) {
			System.out.println("Change pass Success");

			SessionLogin session = new SessionLogin(getActivity());
			session.createLoginSession(ContentManager.getInstance()
					.getCurrentUser().getEmail(), newPass);

			try {
				JSONObject obj = new JSONObject(new String(response));

				Toast.makeText(getActivity(),
						obj.getString("message").toString(), Toast.LENGTH_SHORT)
						.show();

			} catch (Exception ex) {

			}
		}

		@Override
		public void onStart() {
			System.out.println("Start");
		}

		@Override
		public void onFinish() {
			if (dialog != null)
				dialog.dismiss();
		}

		@Override
		public void onFailure(int statusCode, Header[] headers,
				byte[] errorResponse, Throwable e) {
			System.out.println("Change pass logout");
			try {
				JSONObject obj = new JSONObject(new String(errorResponse));

				Toast.makeText(getActivity(),
						obj.getString("message").toString(), Toast.LENGTH_SHORT)
						.show();

			} catch (Exception ex) {

			}
		}
	};
	AsyncHttpResponseHandler handlerLogout = new AsyncHttpResponseHandler() {
		@Override
		public void onSuccess(int statusCode, Header[] headers, byte[] response) {
			System.out.println("Logout Success");

			SessionLogin session = new SessionLogin(getActivity());
			session.setLoginState(false);

			ContentManager.getInstance().isLogin(false);
			startActivity(new Intent(getActivity(), WelcomeActivity.class));
			getActivity().finish();
		}

		@Override
		public void onStart() {
			System.out.println("Start");
		}

		@Override
		public void onFinish() {
			if (dialog != null)
				dialog.dismiss();
		}

		@Override
		public void onFailure(int statusCode, Header[] headers,
				byte[] errorResponse, Throwable e) {
			System.out.println("Fail logout");
			try {
				JSONObject obj = new JSONObject(new String(errorResponse));

				Toast.makeText(getActivity(),
						obj.getString("message").toString(), Toast.LENGTH_SHORT)
						.show();

			} catch (Exception ex) {

			}
		}
	};

	AsyncHttpResponseHandler handlerSetPrivateSetting = new AsyncHttpResponseHandler() {
		@Override
		public void onSuccess(int statusCode, Header[] headers, byte[] response) {
			System.out.println("Logout Success");

			try {
				JSONObject obj = new JSONObject(new String(response));

				Toast.makeText(getActivity(),
						obj.getString("message").toString(), Toast.LENGTH_SHORT)
						.show();

			} catch (Exception ex) {

			}
		}

		@Override
		public void onStart() {
			System.out.println("Start");
		}

		@Override
		public void onFinish() {
			if (dialog != null)
				dialog.dismiss();
		}

		@Override
		public void onFailure(int statusCode, Header[] headers,
				byte[] errorResponse, Throwable e) {
			System.out.println("Fail logout");
			try {
				JSONObject obj = new JSONObject(new String(errorResponse));

				Toast.makeText(getActivity(),
						obj.getString("message").toString(), Toast.LENGTH_SHORT)
						.show();

			} catch (Exception ex) {

			}
		}
	};

}
